import Cookies from 'js-cookie'

const state = {
  sidebar: {
    // Cookies.get( 'sidebarStatus' )本地值‘0'(侧边栏收起)  '1'(侧边栏展开)
    // 知识点:字符串'0'代表true,数字0代表false
    // +'0’+'1'意思:隐式类型转换0数字和1数字
    // !和!1 意思:隐式类型转换，true和false
    // 发现跟原来的意思对应不上了，反了，所以再一次前面加!取反回来
    // 当第一次打开，Cookie里默认无值，取出null（假)，就会使用:后面的值true给opened
    // 效果:默认上来侧边栏打开
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop'
}

const mutations = {
  TOGGLE_SIDEBAR: (state) => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  // 关闭侧边栏
  // 参数1: store对象，我们要提交得store.commit
  // 现在{ commit } = store解构赋值直接拿到commit方法
  // 参数2: layout/index.vue 调用传入对象 { withoutAnimation: false }现在{ withoutAnimation }= { withoutAnimation: false }
  // 左侧withoutAnimation变量值就是false
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  // 切换设备
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
